
#include <stdio.h>
#include "thread.h"

using namespace snda::comm::thread;

CThreadBase::CThreadBase() 
: m_pArg(NULL)
{
	pthread_attr_init(&attr);
}

CThreadBase::~CThreadBase()
{
}

void CThreadBase::Spawn(void* pArg, int iPriority)
{
	m_pArg = pArg;
	struct sched_param param;
	param.sched_priority = iPriority;
	pthread_attr_setschedparam(&attr, &param);
	if(pthread_create(&thread, &attr, CThreadBase::Start, (void*)this))
		perror("Thread create");
}

void CThreadBase::Detach()
{
	pthread_detach(thread);
}

void CThreadBase::Join()
{
	pthread_join(thread, NULL);
}

void CThreadBase::Yield(uint32_t dwTimeMs)
{
	if(dwTimeMs)
	{
		struct timespec rqtp;
		rqtp.tv_sec = 0;
		rqtp.tv_nsec = dwTimeMs * 1000;
		nanosleep(&rqtp, NULL);
	}
	sched_yield();
}

void CThreadBase::LowerPriority()
{
	struct sched_param param;
	int policy;
	pthread_getschedparam(thread, &policy, &param);
	param.sched_priority++;
	pthread_setschedparam(thread, policy, &param);
}

void CThreadBase::RaisePriority()
{
	struct sched_param param;
	int policy;
	pthread_getschedparam(thread, &policy, &param);
	param.sched_priority--;
	pthread_setschedparam(thread, policy, &param);
}

uint32_t CThreadBase::ThrId()
{
	volatile uint32_t v;
	v = (uint32_t) pthread_self() >> 10;
	return v;
}

void* CThreadBase::Start(void* arg)
{
	CThreadBase* pThr = reinterpret_cast<CThreadBase*>(arg);
	return pThr->Run();
}


